import React, { useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Spin, message } from "antd";
import { authService } from "../../services/auth";
import type { SocialLoginType } from "./types";
import styles from "./index.module.less";

/**
 * @description 社交媒体登录回调处理组件
 * @returns {JSX.Element} 回调处理页面
 */
const SocialLoginCallback: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    const handleCallback = async () => {
      try {
        // 从 URL 中获取参数
        const params = new URLSearchParams(location.search);
        const code = params.get("code");
        const state = params.get("state");
        const type = location.pathname.includes("wechat") ? "wechat" : "alipay";

        if (!code || !state) {
          throw new Error("登录参数无效");
        }

        // 处理社交媒体登录
        const result = await authService.handleSocialLogin(
          type as SocialLoginType,
          {
            code,
            state,
          }
        );

        // 保存登录信息
        localStorage.setItem("token", result.token);
        message.success("登录成功");
        navigate("/dashboard");
      } catch (error) {
        message.error(
          error instanceof Error ? error.message : "登录失败，请重试"
        );
        navigate("/login");
      }
    };

    handleCallback();
  }, [location, navigate]);

  return (
    <div className={styles.callbackContainer}>
      <Spin size="large" tip="登录中..." />
    </div>
  );
};

export default SocialLoginCallback;
